import { Directive, ElementRef, OnDestroy, OnInit, EventEmitter } from "@angular/core";
import { InteractiveService } from "./interactive.service";
import { Observable } from "rxjs/Observable";

export const INTERACTIVE_PROP = "isInteractiveItem";

@Directive({
  selector: "[interactive]",
  inputs: [
    "listenEvents",
  ],
  outputs: [
    "eventTrigger"
  ]
})
export class InteractiveDirective implements OnInit, OnDestroy {
  interactiveId = Symbol();
  eventTrigger = new EventEmitter();
  eventSource = new EventEmitter();
  listenEvents: string[];

  constructor(private service: InteractiveService, private elem: ElementRef) {

  }

  ngOnInit() {
    if (this.listenEvents) {
      this.listenEvents.forEach(eventName =>
        this.service.registerMember(this.interactiveId, this.eventSource, eventName)
      );
      this.elem.nativeElement["isInteractiveItem"] = true;
      this.elem.nativeElement.addEventListener("click", e => {
        this.service.setFocusActive(this.interactiveId);
      });

      this.eventSource.catch(err => {
        console.error("Interactive Directive Error: ", err);
        return Observable.empty();
      }).subscribe(payload => {
        if (this.service.getFocusedActive() === this.interactiveId) {
          this.eventTrigger.next(payload)
        }
      });
    }

  }

  ngOnDestroy() {
    // 组件销毁时取消监听
    this.service.unregisterMember(this.interactiveId);
  }

}